'use client'
/**
 * @license 敏捷之道软件
 * 商业用途必须获得书面授权
 * 侵权举报: ideaswork@qq.com
 * 法律依据:《计算机软件保护条例》第二十四条
 */
import { useState, useEffect } from 'react'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { useToast } from "@/hooks/use-toast"

export default function SystemConfigPage() {
  const [apiKey, setApiKey] = useState('')
  const [apiEndpoint, setApiEndpoint] = useState('')
  const [serviceUrl, setServiceUrl] = useState('')
  const [licenseKey, setLicenseKey] = useState('')
  const { toast } = useToast()
  const [isBackingUp, setIsBackingUp] = useState(false)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    const fetchConfig = async () => {
      try {
        const response = await fetch('/api/system/config')
        
        if (!response.ok) {
          throw new Error('Failed to fetch configuration')
        }
        
        const data = await response.json()
        console.log('data', data)
        setApiKey(data.openai.apiKey || '')
        setApiEndpoint(data.openai.baseURL || '')
        setServiceUrl(data.serviceUrl || '')
        setLicenseKey(data.licenseKey || '')
      } catch (error) {
        toast({
          variant: "destructive",
          title: "错误",
          description: error instanceof Error ? error.message : '获取配置失败',
        })
      } finally {
        setIsLoading(false)
      }
    }
    
    fetchConfig()
  }, [toast])

  const handleSaveConfig = async () => {
    try {
      const response = await fetch('/api/system/config', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ apiKey, apiEndpoint, serviceUrl, licenseKey }),
      })

      if (!response.ok) {
        throw new Error('Failed to save configuration')
      }

      toast({
        title: "成功",
        description: "配置已保存",
      })
    } catch (error) {
      toast({
        variant: "destructive",
        title: "错误",
        description: error instanceof Error ? error.message : '保存配置失败',
      })
    }
  }

const handleBackupDatabase = async () => {
  setIsBackingUp(true)
  try {
    const response = await fetch('/api/system/backup', {
      method: 'POST',
    })

    if (!response.ok) {
      throw new Error('Failed to backup database')
    }

    // 获取文件名
    const contentDisposition = response.headers.get('content-disposition')
    const fileName = contentDisposition
      ? contentDisposition.split('filename=')[1].replace(/['"]/g, '')
      : 'backup.db'

    // 获取二进制数据
    const blob = await response.blob()
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    // 释放URL对象
    window.URL.revokeObjectURL(url)

    toast({
      title: "成功",
      description: "数据库备份已下载",
    })
  } catch (error) {
    toast({
      variant: "destructive", 
      title: "错误",
      description: error instanceof Error ? error.message : '备份数据库失败',
    })
  } finally {
    setIsBackingUp(false)
  }
}

  return (
    <div className="container mx-auto py-10">
      <h1 className="text-3xl font-bold mb-8">系统配置</h1>
      {/* <Card className="mb-6">
        <CardHeader>
          <CardTitle>商业版授权</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="apiKey">API Key</Label>
            <Input
              id="licenseKey"
              type="password"
              placeholder="输入 licenseKey"
              value={licenseKey}
              onChange={(e) => setLicenseKey(e.target.value)}
            />
          </div>
          <Button onClick={handleSaveConfig}>保存配置</Button>
        </CardContent>
      </Card> */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>DeepSeek API 配置</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="apiKey">API Key</Label>
            <Input
              id="apiKey"
              type="password"
              placeholder="输入DeepSeek API Key"
              value={apiKey}
              onChange={(e) => setApiKey(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="apiEndpoint">API Endpoint</Label>
            <Input
              id="apiEndpoint"
              type="text"
              placeholder="输入API端点URL"
              value={apiEndpoint}
              onChange={(e) => setApiEndpoint(e.target.value)}
            />
          </div>
          
          <Button onClick={handleSaveConfig}>保存配置</Button>
        </CardContent>
      </Card>
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>服务访问地址</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
       
          <div className="space-y-2">
            <Label htmlFor="serviceUrl">Service URL</Label>
            <Input
              id="serviceUrl"
              type="text"
              placeholder="输入Service URL"
              value={serviceUrl}
              onChange={(e) => setServiceUrl(e.target.value)}
            />
          </div>
          <Button onClick={handleSaveConfig}>保存配置</Button>
          </CardContent>
      </Card>
      <Card>
        <CardHeader>
          <CardTitle>数据库管理</CardTitle>
        </CardHeader>
        <CardContent>
          <Button onClick={handleBackupDatabase} disabled={isBackingUp}>
            {isBackingUp ? '备份中...' : '备份数据库'}
          </Button>
        </CardContent>
      </Card>
    </div>
  )
}